// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#include <cantor/catalog/factory/namespace_info.h>

namespace cantor::catalog {
    turbo::Status NamespaceInfo::merge_for_update(const NamespaceInfo *old_info) {
        return merge_for_update_impl(old_info->_info);
    }

    turbo::Status NamespaceInfo::merge_for_update_impl(const cantor::pb::catalog::NameSpaceInfo &old_info) {
        if (old_info.has_namespace_id() && !_info.has_namespace_id()) {
            _info.set_namespace_id(old_info.namespace_id());
        }
        if (old_info.has_quota() && !_info.has_quota()) {
            _info.set_quota(old_info.quota());
        }

        if (old_info.has_version() && !_info.has_version()) {
            _info.set_version(old_info.version());
        }

        if (old_info.has_deleted() && !_info.has_deleted()) {
            _info.set_deleted(old_info.deleted());
        }

        if (old_info.has_resource_tag() && !_info.has_resource_tag()) {
            _info.set_resource_tag(old_info.resource_tag());
        }

        if (old_info.has_extra() && !_info.has_extra()) {
            *_info.mutable_extra() = old_info.extra();
        }
        return turbo::OkStatus();
    }

    turbo::Result<std::string> NamespaceInfo::serialize() const {
        std::string ret;
        auto r = _info.SerializePartialToString(&ret);
        if (!r) {
            return turbo::data_loss_error("failed to serialize namespace info");
        }
        return ret;
    }

    turbo::Status NamespaceInfo::deserialize(const std::string &data) {
        cantor::pb::catalog::NameSpaceInfo info;
        auto r = info.ParseFromString(data);
        if (!r) {
            return turbo::data_loss_error("failed to parse namespace info");
        }
        _info = std::move(info);
        return turbo::OkStatus();
    }
} // namespace cantor::catalog
